import axios from 'axios';
import router from '../../router/index';
import store from '../../store/index';
import NodeRSA from 'node-rsa';
import md5 from 'blueimp-md5';
import {Message, MessageBox} from 'element-ui';

//api 地址
const prod_host = 'https://merchant.mibaostore.com/rest/v1_2_0/';
const dev_host  = 'https://merchant.mibaostore.cn/rest/v1_2_0/';
//const dev_host  = 'http://192.168.1.250:8181/v1_2_0/';

//oss地址
const prod_osshost = 'https://img.mibaostore.com/';
const dev_osshost = 'https://img.mibaostore.cn/';

export const host = process.env.BUILD_ENV === 'production' ? prod_host : dev_host;
export const osshost = process.env.BUILD_ENV === 'production' ? prod_osshost : dev_osshost;


const rsakey = new NodeRSA({b:512});
const encrypted = rsakey.encrypt('daoben_mibao_bee','base64');

// 创建axios实例
const service = axios.create({
  baseURL: host,
  timeout: 15000,     // 请求超时时间
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  }
});

//判断非空对象
function isEmptyObject(e)
{
  let t;
  for (t in e)
    return !1;
  return !0
}

/**
 * request拦截器
 * 1.添加请求头token
 * 2.get请求数据md5签名防止窜改
 * 3.添加时间戳有效期
 * */
service.interceptors.request.use(config =>
{
  let token = store.getters.token;
  if(token)
  {
    config.headers['token'] = token;
  }
  
  if(config.method.toLowerCase()==='get')
  {
    let params = config.params || {};
    let sign;
    if(!isEmptyObject(params))
    {
      let keys = Object.keys(params).sort();
      let str = keys.map(k => k + '=' + params[k]).join('&');
      sign = md5(str + rsakey.decrypt(encrypted,'utf-8'));
    }
    else
    {
      sign = md5(rsakey.decrypt(encrypted,'utf-8'));
    }
    
    params['sign'] = sign;
    config.params = params;
  }
  
  //console.log(config);
  return config;
}, error =>
{
  // Do something with request error
  console.log(error); // for debug
  Promise.reject(error);
});


//登出操作
const logout = () =>{
  store.dispatch('FedLogOut').then(() =>
  {
    //记录来源页，登录成功后跳回
    let loginFrom = sessionStorage.getItem('LOGIN_FROM');
    if(!loginFrom)
    {
      let currentRoute = router.currentRoute || {name:'Home'};
      //修复登录页操作退出后再次登出的bug
      if(currentRoute.name==="login")
      {
        currentRoute = {name:'Home'};
      }
      
      let route = {
        name:currentRoute.name,
        params:currentRoute.params,
        meta:currentRoute.meta,
        query:currentRoute.query,
      };
      
      sessionStorage.setItem('LOGIN_FROM', JSON.stringify(route));
    }
    
    //跳转到登录页
    router.replace({name:'login'});
  });
};

/*
* 错误信息
* */
const showError = (message)=>{
  //同一时间只提示一个错误信息,默认3秒
  let errorSign = sessionStorage.getItem('SHOW_ERROR') || 0;
  
  if(!errorSign || !JSON.parse(errorSign))
  {
    Message({
      message: message,
      showClose: true,
      type: 'error',
      duration: 4000
    });
    sessionStorage.setItem('SHOW_ERROR',1);
    
  }
  
  setTimeout(()=>{
    sessionStorage.setItem('SHOW_ERROR',0);
  },3000);
};

// respone拦截器
service.interceptors.response.use(
  response =>
  {
    /**
     * response解释
     * code: 200-成功，400-失败，401-重新登录，403-未认证，404-接口不存在，500-服务器内部错误
     * message: 错误信息, SUCCESS表示成功
     */
    const res = response.data;
    
    if (res.code === 200) //200-成功
    {
      return Promise.resolve(res);
    }
    else if (res.code === 401) // 401-重新登录
    {
      //多个接口同时触发401，只报一次
      store.dispatch('Needlogin',true).then(()=>{
        
        return MessageBox.alert('您需要重新登录才能继续操作', '重新登录', {
          confirmButtonText: '重新登录',
          type: 'warning',
          closeOnClickModal:false,
          closeOnPressEscape:false,
        }).then(() =>
        {
          logout();
          
        }).catch(()=>{
          store.dispatch('Needlogin',false);
        });
        
      }).catch((err)=>{
        return Promise.reject(res);
      });
      
    }
    else
    {
      showError(res.message);
      return Promise.reject(res);
    }
  },
  error =>
  {
    showError(error.message);
    return Promise.reject(error);
  }
);

export default service;
